<template>
    <div class="addArticle">
      <el-card class="margin_30" shadow="always" :body-style="{ padding: '20px' }">
        <div slot="header">
          <span>{{$route.query.id ? '编辑' :'新增'}}文章</span>
        </div>
        <!-- card body -->
        <el-form :rules="rules" :model="form" ref="form" size="mini" label-width="80px">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="作者"  prop="author">
                <el-input v-model="form.author"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="标题"  prop="title">
                <el-input v-model="form.title"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="是否显示">
                <el-switch
                  v-model="form.isShow"
                  active-color="#13ce66"
                  inactive-color="#ff4949">
                </el-switch>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="16" :offset="0">
              <el-form-item label="摘要">
                <el-input
                  type="textarea"
                  :rows="2"
                  placeholder=""
                  v-model="form.summary">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="16" :offset="0">
              <el-form-item label="封面图片">
                <el-upload
                  :headers="headers"
                  class="upload-demo"
                  :on-success="getUploadImg"
                  :show-file-list="false"
                  action="/lejuAdmin/material/uploadFileOss"
                  :limit="1"
                >
                  <el-button size="small" type="primary">点击上传</el-button>
                  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                 
                </el-upload>
                <img v-if="form.coverImg" class="pic" :src="form.coverImg" alt="">
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24" :offset="0">
              <el-form-item label="封面图片">
                <!-- <Tinymce :height="300" v-model="form.content1"></Tinymce> -->
                <mavon-editor v-model="form.content1" @change="getVal"  ref=md @imgAdd="$imgAdd"/>
              </el-form-item>
            </el-col>
          </el-row>
        
          <el-form-item>
            <el-button type="primary" @click="onSubmit">立即创建</el-button>
            <el-button>取消</el-button>
          </el-form-item>
        </el-form>
        
      </el-card>
      
    </div>
</template>

<script>
import {
  getToken
} from "@/utils/myAuth"
import {
  uploadFileOss,
  addArticle,
  productArticle,
  updateArticle
} from "@/api/contentManage/addArticle"
import Tinymce from "@/components/Tinymce"
export default {
  components:{
    Tinymce
  },
    data() {
      var checkTitle = (rule, value, callback) => {
        console.log(value);
        if(value.length > 1 && value.length < 5){
          callback();
        }else{
          callback(new Error('标题的长度在1-5之间'));
        }
        // if (value === '') {
        //   callback(new Error('请输入密码'));
        // } else {
        //   if (this.ruleForm.checkPass !== '') {
        //     this.$refs.ruleForm.validateField('checkPass');
        //   }
        //   callback();
        // }
      };
        return {
          headers:{
            token:getToken()
          },
          form:{
            "author": "",
            "collectCount": "",
            "content1": "",
            "content2": "",
            "coverImg": "",
            "createTime": "",
            "editorType": "",
            "id": "",
            "isShow": "",
            "modifyTime": "",
            "summary": "",
            "title": "",
            "viewCount": "",
            "zanCount": ""
          },
          rules: {
            author: [
              { required: true, message: '请输入作者姓名', trigger: 'blur' },
              { min: 1, max: 3, message: '姓名长度为1-3之间', trigger: 'blur' }
            ],
            title:[
             {
              validator:checkTitle, trigger: 'blur'
             }
            ]
          }
        }
    },
    computed: {

    },
    created() {
      if(this.$route.query.id){
        productArticle(this.$route.query.id)
        .then(res=>{
          console.log(res)
          res.data.productArticle.isShow  =  res.data.productArticle.isShow ? true : false
          this.form = res.data.productArticle
        })
      }
     
    },
    mounted() {

    },
    methods: {
      getVal(value,render){
        console.log(value,render)
        this.form.content2 = render
      },
      getUploadImg(response){
        console.log(response)
        this.form.coverImg = response.data.fileUrl;
      },
      onSubmit(){
        this.$refs.form.validate((valid) => {
          if (valid) {
            // this.form.isShow = this.form.isShow ? 1 : 0;
            var formData = JSON.parse(JSON.stringify(this.form));
            formData.isShow = formData.isShow ? 1 : 0;
            if(this.$route.query.id){
              updateArticle(formData)
              .then(res =>{
              console.log(res);
              this.$message({
                message: '文章修改成功',
                type: 'success'
              });
            })
              return
            } 
            addArticle(formData)
            .then(res =>{
              console.log(res);
              this.$message({
                message: '文章提交成功',
                type: 'success'
              });
            })
            
          } else {
            console.log('error submit!!');
            return false;
          }
        });
       
      },
       // 绑定@imgAdd event
       $imgAdd(pos, $file){
            // 第一步.将图片上传到服务器.
           var formdata = new FormData();
           formdata.append('file', $file);
           uploadFileOss(formdata)
           .then(res =>{
            this.$refs.md.$img2Url(pos, res.data.fileUrl);
          })
          //  axios({
          //      url: 'server url',
          //      method: 'post',
          //      data: formdata,
          //      headers: { 'Content-Type': 'multipart/form-data' },
          //  }).then((url) => {
          //      // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)
          //      /**
          //      * $vm 指为mavonEditor实例，可以通过如下两种方式获取
          //      * 1. 通过引入对象获取: `import {mavonEditor} from ...` 等方式引入后，`$vm`为`mavonEditor`
          //      * 2. 通过$refs获取: html声明ref : `<mavon-editor ref=md ></mavon-editor>，`$vm`为 `this.$refs.md`
          //      */
          //      $vm.$img2Url(pos, url);
          //  })
        }
    },
};
</script>

<style scoped lang="scss">
.addArticle{
  .pic{
    width: 100px;
    height: 100px;
  }
}
</style>
